package com.ddm.pay;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;


import com.ddm.pay.R;

public class DDMWebView extends WebView {
    private static final int MAX_LENGTH = 20;
    ProgressBar progressBar;
    private TextView tvTitle;

    public DDMWebView(Context context) {
        this(context, null);
    }

    public DDMWebView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DDMWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initUI();
    }

    public void setShowProgress(boolean showProgress) {
        if (showProgress) {
            progressBar.setVisibility(VISIBLE);
        } else {
            progressBar.setVisibility(GONE);
        }
    }

    public void setTvTitle(TextView tvTitle) {
        this.tvTitle = tvTitle;
    }

    private void initUI() {
        setHorizontalScrollBarEnabled(false);//水平不显示小方块
        setVerticalScrollBarEnabled(false); //垂直不显示小方块
        progressBar = new ProgressBar(getContext(), null, android.R.attr.progressBarStyleHorizontal);
        progressBar.setMax(100);
        progressBar.setProgressDrawable(this.getResources().getDrawable(R.drawable.ddm_progress_bar_states));
        addView(progressBar, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, dip2px(getContext(), 3)));
        initWebViewSettings();
    }

    //   基本的WebViewSetting
    public void initWebViewSettings() {
        setFocusable(true);
        setFocusableInTouchMode(true);
        requestFocusFromTouch();
        requestFocus();
        setWebViewClient(client);
        setWebChromeClient(chromeClient);
        setClickable(true);
        WebSettings webSetting = getSettings();
        webSetting.setJavaScriptEnabled(true);
        // 是否支持缩放
        webSetting.setBuiltInZoomControls(false);
        //支持通过JS打开新窗口
        webSetting.setJavaScriptCanOpenWindowsAutomatically(true);
        // 开启 DOM storage API 功能
        webSetting.setDomStorageEnabled(true);
        //设置可以访问文件
        webSetting.setAllowFileAccess(true);
   /*     LayoutAlgorithm是一个枚举用来控制页面的布局，有三个类型：
        1.NARROW_COLUMNS：可能的话使所有列的宽度不超过屏幕宽度
        2.NORMAL：正常显示不做任何渲染
        3.SINGLE_COLUMN：把所有内容放大webview等宽的一列中*/
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        //支持缩放，默认为true。是下面那个的前提。
        webSetting.setSupportZoom(true);
        //将图片调整到适合webview的大小
        webSetting.setUseWideViewPort(true);
        //支持页面定位
        webSetting.setGeolocationEnabled(true);
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        // 最高渲染优先级
        webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        //需要支持多窗体还需要重写WebChromeClient.onCreateWindow
        webSetting.setSupportMultipleWindows(false);
        webSetting.setAllowFileAccessFromFileURLs(true);
        webSetting.setAllowUniversalAccessFromFileURLs(true);
        webSetting.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);

    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if ((keyCode == KeyEvent.KEYCODE_BACK) && this.canGoBack()) {
            this.goBack(); // goBack()表示返回WebView的上一页面
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private WebChromeClient chromeClient = new WebChromeClient() {
        @Override
        public void onReceivedTitle(WebView view, String title) {
            if (tvTitle == null) {
                return;
            }
            if (TextUtils.isEmpty(title)) {
                tvTitle.setVisibility(GONE);
                return;

            }
            tvTitle.setVisibility(VISIBLE);
            if (title != null && title.length() > MAX_LENGTH) {
                tvTitle.setText(title.subSequence(0, MAX_LENGTH) + "...");
            } else {
                tvTitle.setText(title);
            }
        }

        //监听进度
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            progressBar.setProgress(newProgress);
            if (progressBar != null && newProgress != 100) {

                //Webview加载没有完成 就显示我们自定义的加载图
                progressBar.setVisibility(VISIBLE);

            } else if (progressBar != null) {
                //Webview加载完成 就隐藏进度条,显示Webview
                progressBar.setVisibility(GONE);
            }
        }
    };

    private WebViewClient client = new WebViewClient() {

        //当页面加载完成的时候
        @Override
        public void onPageFinished(WebView webView, String url) {
            super.onPageFinished(webView, url);
        }

        @Override
        public void onReceivedError(WebView webView, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
            super.onReceivedError(webView, webResourceRequest, webResourceError);

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            //返回值是true的时候控制去WebView打开，
            // 为false调用系统浏览器或第三方浏览器
            if (url.startsWith("http") || url.startsWith("https") || url.startsWith("ftp")) {
                return false;
            } else {
                try {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    view.getContext().startActivity(intent);
                } catch (ActivityNotFoundException e) {
                    Toast.makeText(view.getContext(), "手机还没有安装支持打开此网页的应用！", Toast.LENGTH_SHORT).show();
                }
                return true;
            }
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            return super.shouldInterceptRequest(view, request);
        }

    };


    public String getDoMain(String url) {
        String domain = "";
        int start = url.indexOf(".");
        if (start >= 0) {
            int end = url.indexOf("/", start);
            if (end < 0) {
                domain = url.substring(start);
            } else {
                domain = url.substring(start, end);
            }
        }
        return domain;
    }

    public static int dip2px(Context context, float dpValue) {
        float var2 = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * var2 + 0.5F);
    }


}
